import axios, { AxiosResponse } from 'axios'
import moment from 'moment'

function age(birthday: string): number {
    return Math.ceil((moment().diff(moment(birthday), 'month') / 12))
}
function experience(startDate: string): number {
    return Math.ceil((moment().diff(moment(startDate), 'month') / 1.2)) / 10
}

function hasEducationKeywords(raw: keywordsOf<Profile>): raw is { education: keywordsOf<Education> } {
    return raw.education !== undefined
}

function ProfileParser(raw: ProfileRaw): Profile {
    const person = { ...raw, age: age(raw.birthday) }
    const profession = { ...raw.profession, experience: experience(raw.profession.professionStartDate) }
    const projects = raw.projects.map(raw => {
        return { ...raw, name: '', description: '' }
    })
    return { ...person, profession, projects }
}

export default {
    async findProfiles(keywords: keywordsOf<Profile>): Promise<ServiceReturnList<Profile>> {
        let { data: { data, total } } = await axios.get(`/data/profiles.json?${moment().format('YYYYMMDD')}`) as AxiosResponse<ServiceReturnList<ProfileRaw>>

        let profiles = data.map(raw => ProfileParser(raw))

        if (keywords.availability && keywords.availability.availableDate)
            profiles = profiles.filter(profile => {
                return new Date(profile.availability.availableDate) <= new Date(keywords.availability?.availableDate as string)
            })


        if (hasEducationKeywords(keywords))
            if (keywords.education.diploma !== undefined) {
                const diplomas: Diploma[] = keywords.education.diploma.length ? keywords.education.diploma as Diploma[] : [keywords.education.diploma as Diploma]

                profiles = profiles.filter(profile => {
                    return diplomas.includes(profile.education.diploma)
                })
            }

        if (keywords.profession && keywords.profession.experience)
            profiles = profiles.filter(profile => {
                const [min, max] = keywords.profession?.experience as unknown as [number, number]
                return profile.profession.experience >= min
                    && profile.profession.experience <= max
            })

        //TODO:对tags标签的筛选 党建 9.10

        return { status: 200, total, data: profiles }
    },

    async getProfile(id: string): Promise<Profile | undefined> {
        const { data: { data } } = await axios.get(`/data/profiles.json?${moment().format('YYYYMMDD')}`) as AxiosResponse<ServiceReturnList<ProfileRaw>>
        const profileRaw = data.find(profileRaw => profileRaw.id == id)
        console.log(profileRaw);
        return profileRaw ? ProfileParser(profileRaw) : undefined
    },

    async getProject(id: string): Promise<Project | undefined> {
        const { data: { data } } = await axios.get(`/data/projects.json?${moment().format('YYYYMMDD')}`) as AxiosResponse<ServiceReturnList<Project>>
        return data.find(project => project.id == id)
    }
}